package com.crealth.handler;


import java.io.File;
import java.sql.Timestamp;
import java.util.List;
import org.apache.log4j.Logger;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.crealth.ConstantDefine;
import com.crealth.db.ConsumerProductDb;
import com.crealth.db.LoanContractDb;
import com.crealth.manager.LoanContractNoMgr;
import com.crealth.memcached.ConsumerCached;
import com.crealth.memcached.UserCached;
import com.crealth.model.ConsumerInfoModel;
import com.crealth.model.ConsumerProductModel;
import com.crealth.model.LoanContractModel;
import com.crealth.model.UserModel;
import com.crealth.msg.NetMessageData;
import com.crealth.utils.StringUtil;
import com.crealth.utils.Utils;

public class LoanContractHandler {
	//private static Logger logger = Logger.getLogger("running_log");
	private static Logger errorLog = Logger.getLogger("error_log");
	
	//  新增 贷款合同  
	public static NetMessageData addLoanContract(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		int userID = msgJson.getIntValue("id");
		//UserModel user = UserCached.selectUserByID(userID);
		LoanContractModel contract = new LoanContractModel();
		contract.parseFromJson(msgJson);
		int salesManID = contract.getUserID();
		UserModel salesMan = UserCached.selectUserByID(salesManID);
		int belognComID = salesMan.getBelongCompanyID();
		String contctNo = LoanContractNoMgr.getLoanContractNo(belognComID, contract.getApplyForTm());
		contract.setContractNo(contctNo);
		contract.setCompanyID(belognComID);
		
		Integer res = LoanContractDb.insertLoanContract(contract);
		if (res == null) {
			resJson.put("resCode", ErrorCode.ERROR_Add_Fail);
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}
		
		ConsumerCached.updateConsumerStatusByID(contract.getConsumerInfoID(), ConsumerInfoModel.Contract_Saved);
		resJson.put("contractInfo", contract.toJSONObject());
		resJson.put("resCode", 0);
		resJson.put("opUser", userID);
		sendMsg.setMsgBody(resJson.toJSONString());
		sendMsg.setMsgCmd(revData.getMsgCmd());
		int companyID = salesMan.getBelongCompanyID();
		ResponseMsgQueue.sendBranchCompanyMgr(userID, companyID, sendMsg);
		ResponseMsgQueue.sendCompanyTopMgr(userID, sendMsg);
		ResponseMsgQueue.sendMsgToFinance(userID, companyID, sendMsg);
		ResponseMsgQueue.sendMsgToCustomerService(userID, companyID, sendMsg);
		
		return sendMsg;
	}
	
	public static NetMessageData modifyLoanContract(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		int userID = msgJson.getIntValue("id");
		UserModel user = UserCached.selectUserByID(userID);
		LoanContractModel contract = new LoanContractModel();		
		contract.parseFromJson(msgJson);
		int contractID = msgJson.getIntValue("contractID");		
		LoanContractModel eistContract = LoanContractDb.selectLoanContractByID(contractID);
		Integer res = null;
		if (eistContract != null && 
			eistContract.getStatus() < LoanContractModel.Contract_Signed) {
			contract.setId(contractID);
			Timestamp oldApplyTm = eistContract.getApplyForTm();
			String strOldApplyDay = Utils.getYearMonthDay(oldApplyTm.getTime());
			Timestamp applyTm = contract.getApplyForTm();
			String strApplyDay = Utils.getYearMonthDay(applyTm.getTime());
			String contctNo = eistContract.getContractNo();
			contract.setContractNo(eistContract.getContractNo());
			if (!strOldApplyDay.equals(strApplyDay)) {
				contctNo = LoanContractNoMgr.getLoanContractNo(eistContract.getCompanyID(), applyTm);
				contract.setContractNo(contctNo);
				ConsumerProductDb.updateProductNoByContract(contract);
			}
			res = LoanContractDb.updateContractByID(contract);
		} else {
			UserModel salesMan = UserCached.selectUserByID(contract.getUserID());
			int belognComID = user.getBelongCompanyID();
			if (salesMan != null) {
				belognComID = salesMan.getBelongCompanyID();
			}
			String contctNo = LoanContractNoMgr.getLoanContractNo(belognComID, contract.getApplyForTm());
			contract.setContractNo(contctNo);
			contract.setCompanyID(belognComID);
			res = LoanContractDb.insertLoanContract(contract);
		}
		if (res == null) {
			resJson.put("resCode", ErrorCode.ERROR_Add_Fail);
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}
		int setStatus = ConsumerInfoModel.Contract_Saved;
		ConsumerCached.updateConsumerStatusByID(contract.getConsumerInfoID(), setStatus);
		contract = LoanContractDb.selectLoanContractByID(contractID);
		if (contract != null) {
			resJson.put("contractInfo", contract.toJSONObject());
		}
		resJson.put("resCode", 0);
		resJson.put("opUser", userID);
		sendMsg.setMsgBody(resJson.toJSONString());
		sendMsg.setMsgCmd(revData.getMsgCmd());
		int companyID = user.getCompanyID();
		ResponseMsgQueue.sendBranchCompanyMgr(userID, companyID, sendMsg);
		ResponseMsgQueue.sendCompanyTopMgr(userID, sendMsg);
		ResponseMsgQueue.sendMsgToFinance(userID, companyID, sendMsg);
		
		return sendMsg;
	}
	
	//  获取  制定的 贷款合同
	public static NetMessageData obtainLoanContract(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		//int userID = msgJson.getIntValue("id");
		//UserModel user = UserCached.selectUserByID(userID);
		if (!msgJson.containsKey("consumerID")) {
			return null;
		}
		int consumerID = msgJson.getIntValue("consumerID");
		int consumerUserID = msgJson.getIntValue("consumerUserID");
		List<LoanContractModel> contractls = LoanContractDb.selectLoanContractByConsumerID(consumerID, consumerUserID);
		JSONArray jsonArray = new JSONArray();
		for (LoanContractModel contract : contractls) {
			jsonArray.add(contract.toJSONObject());
		}
		
		resJson.put("contractInfo", jsonArray);
		resJson.put("resCode", 0);
		sendMsg.setMsgBody(resJson.toJSONString());			
		return sendMsg;
	}
	
	//  退回  
	public static NetMessageData sendBackConsumer(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		int userID = msgJson.getIntValue("id");
		UserModel user = UserCached.selectUserByID(userID);
		if (!msgJson.containsKey("consumerID")) {
			return null;
		}
		int consumerID = msgJson.getIntValue("consumerID");
		ConsumerInfoModel consumerInfo = ConsumerCached.selectConsumer(consumerID);
		if (consumerInfo == null) {
			return null;
		}
		if (consumerInfo.getStatus() == ConsumerInfoModel.Contract_Signed || 
			consumerInfo.getStatus() == ConsumerInfoModel.Contract_Accepted ) {
			return null;
		}
		if (msgJson.containsKey("contractID")) {
			int contractID = msgJson.getIntValue("contractID");
			LoanContractDb.updateHasDelete(contractID, 1);
			resJson.put("contractID", contractID);
		}
		
		ConsumerCached.updateConsumerStatusByID(consumerID, ConsumerInfoModel.FollowUp);
		ConsumerCached.sendBackConsumerByID(consumerID);
		ConsumerCached.updateConsumerFlowFollowByID(consumerID, ConsumerInfoModel.Flow_Back);
		
		resJson.put("consumerID", consumerID);
		resJson.put("resCode", 0);
		
		sendMsg.setMsgBody(resJson.toJSONString());
		sendMsg.setMsgCmd(revData.getMsgCmd());
		int companyID = user.getCompanyID();
		ResponseMsgQueue.sendBranchCompanyMgr(userID, companyID, sendMsg);
		ResponseMsgQueue.sendCompanyTopMgr(userID, sendMsg);
		ResponseMsgQueue.sendMsgToFinance(userID, companyID, sendMsg);
		
		return sendMsg;
	}
	
	//  删除合同    作废
	public static NetMessageData delContract(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		int userID = msgJson.getIntValue("id");
		UserModel user = UserCached.selectUserByID(userID);
		if (!msgJson.containsKey("consumerID")) {
			return null;
		}
		int consumerID = msgJson.getIntValue("consumerID");
		ConsumerInfoModel consumerInfo = ConsumerCached.selectConsumer(consumerID);
		if (consumerInfo == null) {
			return null;
		}
		if (consumerInfo.getStatus() == ConsumerInfoModel.Contract_Signed || 
			consumerInfo.getStatus() == ConsumerInfoModel.Contract_Accepted ) {
			return null;
		}
		if (msgJson.containsKey("contractID")) {
			int contractID = msgJson.getIntValue("contractID");
			LoanContractDb.updateHasDelete(contractID, 1);
			resJson.put("contractID", contractID);
		}
		ConsumerCached.sendBackConsumerByID(consumerID);
		ConsumerCached.updateConsumerFlowFollowByID(consumerID, ConsumerInfoModel.Flow_Back);
		
		resJson.put("consumerID", consumerID);
		resJson.put("resCode", 0);
		resJson.put("opUser", userID);
		
		sendMsg.setMsgBody(resJson.toJSONString());
		sendMsg.setMsgCmd(revData.getMsgCmd());
		int companyID = user.getCompanyID();
		ResponseMsgQueue.sendBranchCompanyMgr(userID, companyID, sendMsg);
		ResponseMsgQueue.sendCompanyTopMgr(userID, sendMsg);
		ResponseMsgQueue.sendMsgToFinance(userID, companyID, sendMsg);
		
		return sendMsg;
	}
	
	// 已签  合同
	public static NetMessageData signedContract(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		int userID = msgJson.getIntValue("id");
		//UserModel user = UserCached.selectUserByID(userID);
		if (!msgJson.containsKey("consumerID") ||  
			!msgJson.containsKey("contractID")  ) {
			return null;
		}
		int contractID = msgJson.getIntValue("contractID");
		LoanContractModel contract = LoanContractDb.selectLoanContractByID(contractID);
		if (contract == null ) {
			errorLog.info("contract is null contractID: " + contractID);
			return null;
		}
		if (contract.getStatus() == LoanContractModel.Contract_Signed) {
			resJson.put("resCode", ErrorCode.ERROR_Contract_Signed);
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}
		
		int consumerID = msgJson.getIntValue("consumerID");
		//ConsumerInfoModel consumer = ConsumerCached.selectConsumer(consumerID);
		ConsumerCached.updateConsumerStatusByID(consumerID, ConsumerInfoModel.Contract_Signed);
		ConsumerCached.updateConsumerFlowFollowByID(consumerID, ConsumerInfoModel.Flow_Signed);
		LoanContractDb.updateContractStatusByID(contractID, LoanContractModel.Contract_Signed);
		contract.setStatus(LoanContractModel.Contract_Signed);
		//  跟进电话号码  设置为公司已做
		String phoneNum = contract.getPhoneNum1();
		Timestamp signTm = new Timestamp(System.currentTimeMillis());
		if (phoneNum != null && phoneNum.length() == 11) {
			ConsumerCached.updateConsumerTypeByPhoneNum(phoneNum, ConstantDefine.getConsumerTypeName(12));
		}
		ConsumerCached.updateConsumerTypeByID(consumerID, ConstantDefine.getConsumerTypeName(11));
		ConsumerCached.updateSignContractTmByPhoneNum(phoneNum, signTm);
		String strName = contract.getConsumerName();
		String phoneNum1 = contract.getPhoneNum1();
		ConsumerCached.updateConsumerNameAndPhone(consumerID, strName, phoneNum1);
		ConsumerCached.updateConsumerFlowFollowByID(consumerID, ConsumerInfoModel.Flow_Signed);
		
		UserModel belongUser = UserCached.selectUserByID(contract.getUserID());
		ConsumerProductModel product = new ConsumerProductModel();
		product.setCompanyID(contract.getCompanyID());
		product.setProductNo(contract.getContractNo());
		product.setContractID(contractID);
		product.setUserID(contract.getUserID());
		ConsumerProductDb.insertConsumerProduct(product);
		
		resJson.put("productInfo", product.toJSONObject());
		resJson.put("consumerID", consumerID);
		resJson.put("resCode", 0);
		resJson.put("contractInfo", contract.toJSONObject());
		resJson.put("opUser", userID);
		
		sendMsg.setMsgBody(resJson.toJSONString());
		sendMsg.setMsgCmd(revData.getMsgCmd());
		
		int companyID = belongUser.getCompanyID();
		ResponseMsgQueue.sendBranchCompanyMgr(userID, companyID, sendMsg);
		ResponseMsgQueue.sendCompanyTopMgr(userID, sendMsg);
		ResponseMsgQueue.sendMsgToFinance(userID, companyID, sendMsg);
		ResponseMsgQueue.sendMsgToCustomerService(userID, companyID, sendMsg);
		//  通知  客户经理、团队经理
		ResponseMsgQueue.addMsgToQueue(revData.getMsgCmd(), contract.getUserID(), sendMsg);		
		if (belongUser != null && belongUser.getLeaderID() > 0) {
			ResponseMsgQueue.addMsgToQueue(revData.getMsgCmd(), belongUser.getLeaderID(), sendMsg);
		}
		
		return sendMsg;
	}
	
	//  获取 所有 未完成的合同
	public static NetMessageData obtainAllContract(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		int userID = msgJson.getIntValue("id");
		UserModel user = UserCached.selectUserByID(userID);
		
		List<LoanContractModel> contractls = null;
		if (user.getPosition() == ConstantDefine.Installmenter ) {
			String mortgagerName = user.getUserName();
			List<Integer> idls = ConsumerProductDb.selectContractIDsByMortgagerName(mortgagerName);
			if (idls != null && idls.size() > 0) {
				String ids = StringUtil.mergeListIntegerToString(idls, ",");
				contractls = LoanContractDb.selectLoanContractByIDs(ids);
			}
		}
		else if (user.isTopCompany()) {
			contractls = LoanContractDb.selectAllLoanContract();
		}
		else {
			contractls = LoanContractDb.selectLoanContractByCompanyID(user.getBelongCompanyID());
		}
		if (contractls == null || contractls.size() == 0) {
			resJson.put("contractNum", 0);
			resJson.put("resCode", 0);
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}
		
		JSONArray jsonArray = new JSONArray();
		for (int i = 0; i < contractls.size(); ++i) {
			LoanContractModel contract = contractls.get(i);
			jsonArray.add(contract.toJSONObject());
			if (jsonArray.size() == 50 || i == contractls.size()-1) {
				resJson.put("contractArr", jsonArray);
				resJson.put("contractNum", contractls.size());
				resJson.put("resCode", 0);
				sendMsg.setMsgBody(resJson.toJSONString());
				ResponseMsgQueue.addMsgToQueue(revData.getMsgCmd(), userID, sendMsg);
				
				if (jsonArray.size() == 50 ) {
					jsonArray = new JSONArray();
					resJson = new JSONObject();
					sendMsg = new NetMessageData();
				}
			}
		}
		
		return null;	
	}
	
	public static NetMessageData uploadContractFile(NetMessageData revData) {		
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		if (msgJson == null) {
			errorLog.error("uploadContractFile msgJson is null");
			return null;
		}
		int userID = msgJson.getIntValue("id");
		UserModel user = UserCached.selectUserByID(userID);
		String dtype = msgJson.getString("dtype");
		String data = msgJson.getString("data");
		String fileName = msgJson.getString("fileName");
		int contratID = msgJson.getIntValue("paramID");
		LoanContractModel contract = LoanContractDb.selectLoanContractByID(contratID);
		if (contract != null) {
			String strTm = "" + System.currentTimeMillis() / 1000;
			fileName = String.format("%s_%d_%d_%s.pdf", 
					contract.getContractNo(), contract.getId(), contract.getUserID(), strTm.substring(strTm.length()-5));
		}
		String fileDir;
		String osName = Utils.getOSName();
		if (osName.startsWith("Window")) {
			fileDir = "./ContractFile";
			Utils.checkAndCreateDir(fileDir);			
			Utils.checkAndCreateDir(fileDir);
		}
		else {
			fileDir = "/datadisk/webhost/ContractFile";
			Utils.checkAndCreateDir(fileDir);			
			File f = new File(fileDir);
	        f.setWritable(true, false);						
		}
		Utils.saveUploadFile(userID, dtype, data, 
				fileName, fileName, fileDir);
		
		if (contratID > 0) {
			LoanContractDb.updatePdfinfoUpload(contratID, 1);
			LoanContractDb.updateContractFileByID(contratID, fileName);
		}		
		int resCode = 0;		
		resJson.put("resCode", resCode);
		resJson.put("opUser", userID);
		resJson.put("contractID", contratID);
		resJson.put("fileName", fileName);
		sendMsg.setMsgBody(resJson.toJSONString());
		sendMsg.setMsgCmd(NetMessageData.Net_Upload_ContractFile);
		int companyID = user.getCompanyID();
		ResponseMsgQueue.sendBranchCompanyMgr(userID, companyID, sendMsg);
		ResponseMsgQueue.sendCompanyTopMgr(userID, sendMsg);
		ResponseMsgQueue.sendMsgToFinance(userID, companyID, sendMsg);
		ResponseMsgQueue.sendMsgToCustomerService(userID, companyID, sendMsg);
		
		return sendMsg;
	}
	
}
